package com.jy.modules.cims.common.controller;

import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmExcelTemplateService;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.component.tbj.ITBJBusinessClient;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.data.common.dto.TCMmExcelDictionaryDTO;
import com.jy.modules.cims.data.common.dto.TCMmExcelTemplateDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.dto.form.tbj.TbjAuditResulTotalDto;
import com.jy.modules.cims.data.dto.inter.tbj.TBJResponse;
import com.jy.modules.platform.sysdict.impl.SysDictAPImpl;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * @classname: TCMmLoanDetailController
 * @description: 定义  贷款明细 控制层
 * @author:  zhiqiang
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmLoanDetail")
public class TCMmLoanDetailController extends BaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmLoanDetailController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
    private TCMmLoanDetailService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;
	
    @Autowired
	@Qualifier("com.jy.modules.cims.component.tbj.TBJBusinessClient")
	private ITBJBusinessClient iTBJBusinessClient;
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQuery".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/loanDealManage/queryTCMmLoanDetail");
        }else if("toBackLoanOfferUpdate".equals(operate)){//跳转至贷款交易报盘管理修改页面
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String idDeal = this.getParameterString("idDeal");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode); 
        	model.addObject("idDeal", idDeal);
        	model.setViewName("cims/loanDealManage/updateTCMmLoanlOfferManage");
        }
        
        return model;
    }
    
    /**
     * @author zhiqiang
     * @description:查询分页列表
     * @date 2015-01-12 20:32:17
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmLoanDetail")
    @ResponseBody
    public DataMsg queryListTCMmLoanDetail(HttpServletRequest request, TCMmLoanDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	
    	//查询未使用额度明细状态未使用
    	if(dto.getLoanStatus().equals(CimsConstant.QUOTA_LOAN_DETAI_STATUS_NOT)){
    		dto.setQuotaLoanStatus(CimsConstant.QUOTA_LOAN_DETAI_STATUS_NOT);
    		dto.setLoanStatus("");
    		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
    	}
    	
    	//查询作废额度明细状态未使用
    	if(dto.getLoanStatus().equals(CimsConstant.QUOTA_LOAN_DETAI_STATUS_RETURN)){
    		dto.setQuotaLoanStatus(CimsConstant.QUOTA_LOAN_DETAI_STATUS_RETURN);
    		dto.setLoanStatus("");
    		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_INVALID);
    	}
    	
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmLoanDetailDTO> list = service.searchTCMmLoanDetailByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    /**
     * @description:验证贷款信息是否推送
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isPropellingMovement")
    @ResponseBody
    public void isPropellingMovement(HttpServletResponse response,TCMmLoanDetailDTO dto) throws Exception {
  
    	Map<String, Object> result = new HashMap<String, Object>();
    	Writer out = response.getWriter();
    	
		TCMmLoanDetailDTO tCMmLoanDetailDTO = service.queryTCMmLoanDetailByContractNo(dto.getContractNo());
		String loanEachStatus="";
		if(tCMmLoanDetailDTO!=null){
			loanEachStatus = tCMmLoanDetailDTO.getLoanEachStatus();
		}
        
		result.put("loanEachStatus", loanEachStatus);
		out.write(JSON.toJSONString(result));
    }
    
    /**
     * @author zhoupeng
     * 导出贷款明细的查询结果
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/exportLoanDetail")
	@ResponseBody
    public void exportLoanDetail(HttpServletRequest request,HttpServletResponse response, TCMmLoanDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "贷款明细"+dealDate;
		Map<String, Object> searchParams = new HashMap<String, Object>();
    	//查询未使用额度明细状态未使用
    	if(dto.getLoanStatus().equals(CimsConstant.QUOTA_LOAN_DETAI_STATUS_NOT)){
    		dto.setQuotaLoanStatus(CimsConstant.QUOTA_LOAN_DETAI_STATUS_NOT);
    		dto.setLoanStatus("");
    		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_NEW);
    	}
    	//查询作废额度明细状态未使用
    	if(dto.getLoanStatus().equals(CimsConstant.QUOTA_LOAN_DETAI_STATUS_RETURN)){
    		dto.setQuotaLoanStatus(CimsConstant.QUOTA_LOAN_DETAI_STATUS_RETURN);
    		dto.setLoanStatus("");
    		dto.setDealStatus(CimsConstant.QUOTA_DETAIL_STATUS_INVALID);
    	}
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<TCMmLoanDetailDTO> list = service.searchTCMmLoanDetailExport(params.getSearchParams());
        
		
		
    	ExportAndImport<TCMmLoanDetailDTO> exportAndImport = new ExportAndImport<TCMmLoanDetailDTO>();
    	String columnCode = CimsConstant.LOADDEATIL_RESULT_EXPORT_CODE;
    	String columnName = CimsConstant.LOADDEATIL_RESULT_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.LOADDETAIL_FORM_FAILED + ":贷款明细导出结果" + e);
		}
    }
    
   
    /**
  	 * 页面输出
  	 * 
  	 * @param workbook
  	 * @param fileName
  	 * @param response
  	 * @throws IOException
  	 */
  	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

  		try {
  			
  			response.setContentType("application/vnd.ms-excel");
  			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
  			response.setCharacterEncoding("UTF-8");
  			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
  			workbook.write(response.getOutputStream());
  			response.getOutputStream().flush();
  		} catch (Exception e) {
  			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
  		} finally {
  			response.getOutputStream().close();
  		}
  	}

    /**
     * @author zhiqiang
     * @description:新增
     * @date 2015-01-12 20:32:17
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmLoanDetail")
    @ResponseBody
    public DataMsg insertTCMmLoanDetail(HttpServletRequest request, TCMmLoanDetailDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmLoanDetailDTO)super.initDto(dto);

            service.insertTCMmLoanDetail(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:编辑
     * @date 2015-01-12 20:32:17
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmLoanDetail")
    @ResponseBody
    public DataMsg updateTCMmLoanDetail(HttpServletRequest request, TCMmLoanDetailDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmLoanDetailDTO)super.initDto(dto);
           
            service.updateTCMmLoanDetail(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:删除
     * @date 2015-01-12 20:32:17
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmLoanDetail")
    @ResponseBody
    public DataMsg deleteTCMmLoanDetail(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmLoanDetailByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    
    /**
     * 
     * @Description 
     * @param request
     * @param dataMsg
     * @return   
     * DataMsg  
     * @throws
     * @author zhangmi
     * @date 2016-6-14
     */
    @RequestMapping(value = "/getTbjLoanDetailStatus")
    @ResponseBody
    public DataMsg getTbjLoanDetailStatus(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
   	 	String contractNo = (String) this.getParameter("contractNo");
   	 	String type = (String) this.getParameter("type");
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			TBJResponse tBJResponse = new TBJResponse();
			 //service.deleteTCMmLoanDetailByPrimaryKey(dto,ids);
			if("1".equals(type)){
				tBJResponse = iTBJBusinessClient.searchAudit(contractNo);
			}else if("2".equals(type)){
				tBJResponse = iTBJBusinessClient.searchLoan(contractNo);
			}
			dataMsg.setMsg(JSONObject.toJSONString(tBJResponse));
		} catch (Exception e) {
			dataMsg.setMsg(ExceptionUtils.getStackTraceAsString(e));
			dataMsg.failed(e.getMessage());
			logger.error("执行方法getTbjLoanDetailStatus异常：", e);

		}
        return dataMsg;
    }
    /**
     * @author zhiqiang
     * @description:通过主键查询 其明细信息
     * @date 2015-01-12 20:32:17
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmLoanDetailDTO dto = service.queryTCMmLoanDetailByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
}
